﻿using Shop.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using WxApi.ApiPay;

namespace Shop.TestPay
{
    public partial class JsPayPage : System.Web.UI.Page
    {
        public static string wxJsApiParam { get; set; } //H5调起JS API参数

        private System.Timers.Timer payTimer;
        private static string cSocde { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            #region 支付界面授权后获取当前操作人的openid
            string code = Request["code"];//授权信息
            //string token = Request["token"];//用户登录凭证
            string openid = Common.HandleWx.getOpenId(code);//获取授权界面的code
            var getvalue = Common.HandleCookie.GetCookieValue("openid");
            if (getvalue.Length > 0) Common.HandleCookie.ClearCookie("openid");
            Common.HandleCookie.SetCookie("openid", openid);//["openid"] = openid;
            #endregion  支付界面授权后获取当前操作人的openid
            if (!IsPostBack)
            {
                #region 支付参数设置
                //string openid = Common.HandleCookie.GetCookieValue("UseOpenId");//客户Openid
                string cSOCode =  Guid.NewGuid().ToString().Substring(0,5);//商户订单号
                string total_fee ="1";//订单总金额
                string goods_tag = "在线支付测试";//商品标记
                string body = "在线支付测试";//商品描述
                string attach = "";//附加数据
                                   //校验支付参数
                string Error = wxPayJSPApi.WxJsValid(openid, cSOCode, total_fee, goods_tag, body);
                System.Reflection.MethodBase.GetCurrentMethod().WriteErrLog("Error:" + Error, "WEIXINPAY");//记录日志功能
                if (Error.Length > 0) { Response.Write(Error);Response.End(); }

                #endregion 支付参数设置

                #region 校验当前订单
                string returnStr = IsHandleSoCode(cSOCode);
                if (returnStr != "支付") { Response.Write(Error); Response.End(); }
                #endregion 校验当前订单

                //JSAPI支付预处理
                try
                {
                    #region 调取统一下单 获取JSAPI的参数值
                    var dic = wxPayJSPApi.WxJSPay(openid, cSOCode, total_fee, goods_tag, body, attach);
                    string json = (new JavaScriptSerializer()).Serialize(dic);
                    System.Reflection.MethodBase.GetCurrentMethod().WriteErrLog("WxPayData:" + json, "WEIXINPAY");//记录日志功能
                    string result = dic["result"].GetVal_String();
                    string resultdetail = dic["resultdetail"].GetVal_String();
                    if (result == "-1") { Response.Write(resultdetail); Response.End(); }
                    string JSAPI = dic["JSAPI"].GetVal_String();//统一单后传入JS方法的参数
                    wxJsApiParam = JSAPI;
                    amount.Text  = total_fee;
                    #endregion 调取统一下单 获取JSAPI的参数值
                    #region 判断订单是否已付款 若已付款，则显示付款成功界面
                    cSocde = cSOCode;
                    payTimer = new System.Timers.Timer(3000);//周期为三秒
                    payTimer.Elapsed += PayTimer_Elapsed;
                    payTimer.AutoReset = true;
                    payTimer.Enabled = true;
                    payTimer.Start();
                    #endregion 判断订单是否已付款 若已付款，则显示付款成功界面
                }
                catch (Exception ex)
                {
                    Response.Write("<span style='color:#FF0000;font-size:20px'>" + "下单失败，请返回重试:" +ex.Message+ "</span>");
                    submit.Visible = false;
                }
             
            }
        }
       
        /// <summary>
        /// 周期执行方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PayTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            string sql = "";
            sql = string.Format(@" SELECT COUNT(1) FROM dbo.[SoPreWxPay] WHERE [cSOCode]='{0}'", cSocde);
            var obj = HandleSQL.getObj(sql.ToString());
            int _obj = obj.GetVal_Int();
            if (_obj > 0)//当已成功后的界面
            {
                payDiv.Visible = false;
                paySuc.Visible = true;
                payTimer.Enabled = false;
                payTimer.Close();
                payTimer.Dispose();
            }
        }
        /// <summary>
        /// 1.校验订单是否存在
        /// 2.校验订单为取消订单
        /// 3.校验订单是否已付款
        /// </summary>
        /// <param name="cSOCode">订单号</param>
        /// <returns></returns>
        private string IsHandleSoCode(string cSOCode)
        {
            string returnStr = "支付";
            string sql = "";
            ////校验订单是否为取消订单
            //sql = string.Format("SELECT cSOCode,IDCus,iStatus FROM dbo.SOPre WHERE cSOCode='{0}'", cSOCode);
            //var dt = HandleSQL.GetData(sql);
            //if (dt == null || dt.Rows == null || dt.Rows.Count == 0) return "不存在此订单";
            //int iStatus = dt.Rows[0]["iStatus"].GetVal_Int();//获取订单的状态
            //if (iStatus == -1) return "此订单已取消，不可支付";
            //校验订单是否已付款
            sql = string.Format(@" SELECT COUNT(1) FROM dbo.[SoPreWxPay] WHERE [cSOCode]='{0}'", cSOCode);
            var obj = HandleSQL.getObj(sql.ToString());
            int _obj = obj.GetVal_Int();
            if (_obj > 0)
            {
                 return  "订单已付款";
            }
            return returnStr;
        }
    }
}